package com.example.bookshop.controller;

import com.example.bookshop.entity.Book;
import com.example.bookshop.entity.User;
import com.example.bookshop.service.AdminService;
import com.example.bookshop.service.UserService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月04日19:17
 */
@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminBookController {

    @Resource
    private AdminService adminService;

    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @GetMapping
    public String adminPage(@RequestParam(defaultValue = "") String keyword,
                            @RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "3") int size,
                            Model model) {
        int offset = (page - 1) * size;
        List<Book> books = adminService.searchBooks(keyword, offset, size);
        int total = adminService.countBooks(keyword);

        model.addAttribute("books", books);
        model.addAttribute("keyword", keyword);
        model.addAttribute("page", page);
        model.addAttribute("totalPages", (int) Math.ceil((double) total / size));
        return "admin";
    }

    @PostMapping("/add")
    public String addBook(Book book) {
        adminService.insert(book);
        return "redirect:/admin";
    }

    @PostMapping("/update")
    public String updateBook(Book book) {
        adminService.updateBook(book);
        return "redirect:/admin";
    }

    @PostMapping("/delete")
    public String deleteBook(@RequestParam("id") Integer id) {
        adminService.deleteById(id);
        return "redirect:/admin";
    }

    @PostMapping("/user/add")
    public String addUser(@RequestParam String username,
                          @RequestParam String password,
                          @RequestParam String role) {
        User user = new User();
        user.setUsername(username);
        // 加密密码
        user.setPassword(passwordEncoder.encode(password));
        user.setRole(role);
        userService.insert(user);
        return "redirect:/admin";
    }

}
